export default {
  data() {
    return {
      userName: '',
      userMobile: '',
      gender: null, //性别
      addCarShow: false, // 显示添加车辆弹框
      checkedServeTypes: [], // 已勾选的服务类型
      checkedQueueTypes: [], // 已勾选的排队类型
      scanFlag: false, //扫描标识s
      sacnType: '', //shot-车牌 vin-vin
      carInfo: {},
      keyboardShow: false, //车牌键盘
      keyboardMode: 'car', //键盘输入的类型
      mode: 'car', //键盘传入的类型
      cancelBtn: false, //键盘取消按钮
      confirmBtn: false, //键盘确认按钮
      showABC: false, //键盘显示为英文
      abbrName: '川', //车牌前
      carNum: '', //车牌后
      // lyBDOCR: null, //图片识别插件
      // platform: '', //手机系统
      isPackage: 0, //是否使用优惠 0 无 1 福利包 2 优惠券
      packageId: '', //福利包id
      // isAddCar: true, //选择车辆页面是否显示添加车辆按钮
      pageLoading: false, //初始化加载效果
    }
  },

  computed: {
    serveTypes() {
      return this.$store.state.afterSales.serveTypes
    },

    queueTypes() {
      return this.$store.state.afterSales.queueTypes
    },

    hadCarNumber() {
      return this.$store.state.afterSales.carLists.length
    },
  },

  onLoad(e) {
    this.userName = this.$store.state.afterSales.userName
    this.userMobile = this.$store.state.afterSales.userMobile
    this.carInfo = this.$store.state.afterSales.arrivalCar
    this.isPackage = Number(e.isPackage)
    this.packageId = e.packageId ? e.packageId : ''
    // console.log(e.isNeedAddCar, this.isPackage, e.isNeedAddCar === 'false')
    // if (e.isNeedAddCar && e.isNeedAddCar === 'false' && this.isPackage === 1) {
    //   this.isAddCar = false
    // }
    if (this.carInfo.milage == 0) {
      this.carInfo.milage = ''
    }
    if (this.carInfo.carNum) {
      this.abbrName = this.carInfo.carNum.slice(0, 1)
      this.carNum = this.carInfo.carNum.slice(1)
    }

    // #ifdef APP-PLUS
    //引用插件
    // this.lyBDOCR = uni.requireNativePlugin('longyoung-BDOCR')
    // this.platform = uni.getSystemInfoSync().platform
    // #endif

    //手动选择车型监听
    uni.$on('specifAll', data => {
      console.log(data)
      this.$set(
        this.carInfo,
        'carName',
        data.brand_Name + ' ' + data.car_Type_Name + ' ' + data.car_Name
      )
      this.$set(
        this.carInfo,
        'brandImg',
        'https://files.yzsheng.com/goodimg/brandimg/' + data.brand_Id + '.png'
      )
      this.$set(this.carInfo, 'carId', data.car_Id)
      this.carInfo.carNum = ''
      this.carInfo.milage = ''
      this.carInfo.vin = ''
      this.carInfo.engine = ''
      this.carNum = ''
    })
    //已有爱车选择监听
    uni.$on('selCar', data => {
      console.log(data)
      this.carInfo = { ...data }
      if (data.milage === '0.00') {
        this.carInfo.milage = ''
      }
      if (data.carNum) {
        this.abbrName = data.carNum.slice(0, 1)
        this.carNum = data.carNum.slice(1)
      } else {
        this.carNum = ''
      }
    })
    this.$nextTick(() => {
      this.pageLoading = true
    })
  },

  // onShow() {
  //   if (this.scanFlag) {
  //     this.readPic2()
  //   }
  // },

  beforeDestroy() {
    uni.$off('selCar')
    uni.$off('specifAll')
    this.$store.commit('afterSales/resetCar')
  },

  methods: {
    // 添加车辆 ， 选择添加方式
    selectAddType() {
      if (this.hadCarNumber) {
        //车辆列表
        uni.navigateTo({
          url: '/pages_afterSales/myLoveCar/myLoveCar',
          // '/pages_afterSales/myLoveCar/myLoveCar?isAddCar=' + this.isAddCar,
        })
      } else {
        this.addCarShow = true
      }
    },

    // 跳转到添加/切换车辆页面，选择车辆
    goSelectCarPage() {
      this.addCarShow = false
      uni.navigateTo({
        url: '/pages_afterSales/addYourCar/addYourCar',
      })
    },

    // 跳转到相机扫描
    goScan(type) {
      if (this.addCarShow) {
        this.addCarShow = false
      }
      // #ifdef APP-PLUS
      this.scanType = type
      this.scanFlag = true
      // let param = type ? `?type=${type}` : ''
      // uni.navigateTo({
      //   url: '/pages_common/scan/scan' + param,
      // })
      uni.navigateTo({
        url: '/pages_common/ocr/ocr?type=' + type,
        success: () => {
          uni.$once('ocr', data => {
            console.log(data)
            if (this.scanType === 'vin') {
              this.$set(this.carInfo, 'vin', data.slice(0, 17))
              this.getCarInfoByVin(data.slice(0, 17))
            } else {
              this.$set(this.carInfo, 'carNum', data.slice(0, 8))
              this.abbrName = data.slice(0, 1)
              this.carNum = data.slice(1, 8)
            }
          })
        },
      })

      // #endif
      // #ifndef APP-PLUS
      uni.showToast({
        title: '浏览器暂不支持该功能',
        icon: 'none',
      })

      // #endif
    },

    //扫描读取图片信息(用插件读取图片信息)
    readPic(type) {
      // this.lyBDOCR.startOCRLy(
      //   {
      //     type: type,
      //     accuracy: 'auto', //支持这三个字符串：auto、normal、high，精准度，精度越高，速度越慢。default：auto
      //   },
      //   (result) => {
      //     uni.showLoading({
      //       title: '识别中',
      //     })
      //     let number = ''
      //     if (this.platform === 'ios') {
      //       number = type === 107 ? result.result[0].words : result.number
      //     } else {
      //       number = result.text ? result.text.replace(/[\n]/g, '') : ''
      //     }
      //     uni.hideLoading()
      //     if (number.length) {
      //       if (type === 107) {
      //         this.carInfo.vin = number.slice(0, 17)
      //         this.getCarInfoByVin(this.carInfo.vin)
      //       } else {
      //         this.$set(this.carInfo, 'carNum', number.slice(0, 8))
      //         this.abbrName = number.slice(0, 1)
      //         this.carNum = number.slice(1, 8)
      //       }
      //     }
      //   }
      // )
    },

    //读取图片信息(从接口读取图片信息)
    readPic2() {
      this.scanFlag = false
      // const img = uni.getStorageSync('isVal')
      // if (!img) {
      //   return
      // }
      // uni.showLoading({
      //   title: '识别中',
      // })
      // const errFn = () => {
      //   uni.hideLoading()
      //   uni.showToast({
      //     title: '请确保当前识别的车牌/VIN号四边完整，清晰无遮挡物',
      //     icon: 'none',
      //   })
      // }
      // uni.compressImage({
      //   src: img,
      //   quality: 35,
      //   success: async (res) => {
      //     let imgUrl
      //     try {
      //       imgUrl = await this.$api.files.uploadImg({
      //         filePath: res.tempFilePath,
      //       })
      //       if (this.sacnType === 'vin') {
      //         this.vinImgHandle(imgUrl.baseUrl + imgUrl.url, errFn)
      //       } else {
      //         this.carNumberHandle(imgUrl.baseUrl + imgUrl.url, errFn)
      //       }
      //     } catch (e) {
      //       errFn()
      //     }
      //   },
      // })
    },

    async vinImgHandle(imgUrl, errFn) {
      try {
        let imgInfo = await this.$api.accessory.getVin({
          imageFilePath: imgUrl,
        })
        if (imgInfo.data.status === 1) {
          errFn()
        } else {
          this.carInfo.vin = imgInfo.data.vin
          uni.hideLoading()
          this.getCarInfoByVin(imgInfo.data.vin)
        }
      } catch (e) {
        console.log(e)
        errFn()
      }
    },

    async carNumberHandle(imgUrl, errFn) {
      try {
        let imgInfo = await this.$api.afterSales.getCarNumber({
          pic: imgUrl,
          picType: '1', //0、base64编码 1、url地址
        })
        console.log(imgInfo)
        if (imgInfo.data.status === 1) {
          errFn()
        } else {
          this.$set(this.carInfo, 'carNum', imgInfo.data[0])
          uni.hideLoading()
        }
      } catch (e) {
        console.log(e)
        errFn()
      }
    },

    //vin获取车辆信息
    getCarInfoByVin(vin) {
      this.$api.afterSales
        .getCarInfoByVin({ vin })
        .then(res => {
          console.log(res.data)
          if (res.data.carName) {
            this.$set(this.carInfo, 'carName', res.data.carName)
            if (res.data.brandImg) {
              this.$set(this.carInfo, 'brandImg', res.data.brandImg)
            }
          }
          if (res.data.engine) {
            this.$set(this.carInfo, 'engine', res.data.engine)
          }
          this.$set(this.carInfo, 'vin', vin)
        })
        .catch(e => {
          console.log(e)
        })
    },

    // 监听服务类型多选
    serveTypeChange(e) {
      this.checkedServeTypes = e
    },

    // 监听排队类型多选
    queueTypeChange(e) {
      this.checkedQueueTypes = e
    },

    //选择别
    selGender(data) {
      if (data === this.gender) {
        this.gender = null
      } else {
        this.gender = data
      }
    },

    showKeyBoard(mode) {
      this.keyboardShow = true
      this.keyboardMode = mode
      if (mode === 'car') {
        this.confirmBtn = false
        this.cancelBtn = false
        this.showABC = false
        this.mode = 'car'
      } else {
        this.confirmBtn = true
        this.cancelBtn = true
        this.showABC = true
        if (mode === 'number' || mode === 'tel') {
          this.mode = 'number'
        } else {
          this.mode = 'car'
        }
      }
    },

    //输入
    keyboardChange(e) {
      if (this.keyboardMode === 'car') {
        this.abbrName = e
        this.keyboardShow = false
        this.carInfo.carNum = this.abbrName + this.carNum
      } else if (this.keyboardMode === 'number') {
        if (!this.carInfo.milage) {
          this.$set(this.carInfo, 'milage', e + '')
        } else if ((this.carInfo.milage + '').length < 8) {
          this.carInfo.milage = this.carInfo.milage + '' + e
        }
      } else if (this.keyboardMode === 'tel') {
        if ((this.userMobile + '').length < 11)
        {this.userMobile = this.userMobile ? this.userMobile + '' + e : e}
      } else if (this.keyboardMode === 'vin') {
        if (!this.carInfo.vin) {
          this.$set(this.carInfo, 'vin', e + '')
        } else if ((this.carInfo.vin + '').length < 17) {
          this.carInfo.vin = this.carInfo.vin + '' + e
        }
      } else if (this.keyboardMode === 'engine') {
        if (!this.carInfo.engine) {
          this.$set(this.carInfo, 'engine', e + '')
        } else if ((this.carInfo.engine + '').length < 25) {
          this.carInfo.engine = this.carInfo.engine + '' + e
        }
      } else if (this.keyboardMode === 'carNum') {
        if (this.carNum.length < 7) {
          this.carNum = this.carNum + '' + e
          this.carInfo.carNum = this.abbrName + this.carNum
        }
      }
      this.$forceUpdate()
    },

    backspace() {
      if (this.keyboardMode === 'number') {
        if (typeof this.carInfo.milage === 'number') {
          this.carInfo.milage = this.carInfo.milage + ''
        }
        if (this.carInfo.milage.length) {
          this.carInfo.milage = this.carInfo.milage.slice(0, -1)
        }
      } else if (this.keyboardMode === 'tel') {
        this.userMobile = this.userMobile.slice(0, -1)
      } else if (this.keyboardMode === 'vin') {
        if (this.carInfo.vin.length) {
          this.carInfo.vin = this.carInfo.vin.slice(0, -1)
        }
      } else if (this.keyboardMode === 'engine') {
        if (this.carInfo.engine.length) {
          this.carInfo.engine = this.carInfo.engine.slice(0, -1)
        }
      } else if (this.keyboardMode === 'carNum') {
        if (this.carNum.length) {
          this.carNum = this.carNum.slice(0, -1)
          this.carInfo.carNum = this.abbrName + this.carNum
        }
      }
      this.$forceUpdate()
    },

    //键盘确认/取消事件
    keyboardConfirm() {
      if (this.keyboardMode === 'tel') {
        if (!this.userMobile) {
          uni.showToast({
            title: '请填写联系电话',
            icon: 'none',
          })
        }
        if (!/^1[3456789]\d{9}$/.test(this.userMobile)) {
          uni.showToast({
            title: '请填写正确的联系电话',
            icon: 'none',
          })
        }
      } else if (this.keyboardMode === 'vin') {
        this.vincheck()
      } else if (this.keyboardMode === 'engine') {
        // if (!this.carInfo.engine) {
        //   uni.showToast({
        //     title: '请填写发动机号',
        //     icon: 'none',
        //   })
        // }
      } else if (this.keyboardMode === 'carNum') {
        if (this.carNum.length < 6) {
          uni.showToast({
            title: '请填写正确车牌',
            icon: 'none',
          })
        }
      }
      this.$forceUpdate()
    },

    //填写车牌号失焦
    changeCarNum() {
      this.carInfo.carNum = this.abbrName + this.carNum
    },

    // 确认创建
    confirm() {
      if (!this.checkData()) {
        return
      }
      uni.showLoading({ title: '创建中' })
      if (this.isPackage) {
        this.$store.commit('afterSales/setCar', {
          img: this.carInfo.brandImg,
          name: this.carInfo.carName,
          carbrand: this.carInfo.carNum, // 车牌
          km: this.carInfo.milage, // 公里数
          vin: this.carInfo.vin,
          tireSize: '', //轮胎规格
          carId: this.carInfo.carId, //车辆id
          loveCarId: this.carInfo.carId, //车辆id
          engineType: this.carInfo.engine, //发动机号
        })
        this.$store.commit('afterSales/setUserInfo', {
          name: this.userName || '客户' + this.userMobile.slice(7),
          mobile: this.userMobile,
        })
      }
      this.$api.afterSales
        .creatArrival({
          carName: this.carInfo.carName,
          carNum: this.carInfo.carNum,
          mileage: this.carInfo.milage,
          vin: this.carInfo.vin,
          engineType: this.carInfo.engine,
          userName: this.userName || '客户' + this.userMobile.slice(7),
          userMobile: this.userMobile,
          serviceType: this.checkedServeTypes,
          queueType: this.checkedQueueTypes,
          sex: this.gender,
        })
        .then(res => {
          uni.hideLoading()
          uni.showToast({
            title: '到店单创建成功',
            duration: 2000,
          })
          setTimeout(() => {
            if (this.isPackage === 0) {
              uni.redirectTo({
                url: '/pages_afterSales/arrivalRecordList/arrivalRecordList',
              })
            } else if (this.isPackage === 1) {
              uni.redirectTo({
                url:
                  '/pages_afterSales/selectSetMenu/selectSetMenu?type=1&packageId=' +
                  this.packageId +
                  '&id=' +
                  res.data,
              })
            } else {
              uni.redirectTo({
                url:
                  '/pages_afterSales/createMaintenanceOrder/createMaintenanceOrder',
              })
            }
          }, 2000)
        })
        .catch(e => {
          uni.hideLoading()
          console.log(e)
        })
    },

    //提交数据检查
    checkData() {
      let errToase = title => {
        uni.showToast({
          title: title,
          icon: 'none',
        })
      }
      if (!this.carInfo.carName) {
        errToase('请选择车辆')
        return false
      }
      if (!this.carInfo.carNum) {
        errToase('请填写车牌')
        return false
      }
      if (this.carInfo.carNum.length < 6) {
        errToase('请填写正确车牌')
        return false
      }
      if (!this.carInfo.milage || this.carInfo.milage < 0.01) {
        errToase('请填写车辆里程')
        return false
      }
      if (!this.carInfo.vin) {
        errToase('请填写VIN')
        return false
      }
      if (!/^[A-HJ-NPR-Z\d]{17}$/.test(this.carInfo.vin)) {
        errToase('请填写正确的VIN')
        return false
      }
      // if (!this.carInfo.engine) {
      //   errToase('请填写发动机号')
      //   return false
      // }
      // if (this.carInfo.engine.length < 10) {
      //   errToase('请填写正确的发动机号')
      //   return false
      // }
      // if (!this.userName) {
      //   errToase('请填写客户姓名')
      //   return false
      // }
      if (!this.userMobile) {
        errToase('请填写联系电话')
        return false
      }
      if (!/^1[3456789]\d{9}$/.test(this.userMobile)) {
        errToase('请填写正确的联系电话')
        return false
      }
      if (!this.checkedServeTypes.length) {
        errToase('请选择服务类型')
        return false
      }
      if (!this.checkedQueueTypes.length) {
        errToase('请选择排队类型')
        return false
      }
      return true
    },

    vincheck() {
      if (this.carInfo.vin) {
        this.carInfo.vin = this.carInfo.vin.toUpperCase()
      }

      const exp = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{17}$/
      if (!exp.test(this.carInfo.vin)) {
        uni.showToast({
          title: '请输入正确的vin码',
          icon: 'none',
        })
      }
    },

    vinInput(e) {
      this.carInfo.vin = e.detail.value.replace(/[\W]/g, '')
    },

    engineInput(e) {
      this.carInfo.engine = e.detail.value.replace(/[\W]/g, '')
    },
  },
}
